<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
      :disabled="disabled"
    >
      <!-- 采购计划编号下拉框（优化：初始加载200条+完整过滤） -->
      <el-form-item label="采购计划编号" prop="purchasePlanNo">
        <el-select
          v-model="formData.purchasePlanNo"
          filterable
          placeholder="请选择采购计划编号"
          :filter-method="handlePlanFilter"
          v-loading="planLoading"
          :disabled="disabled"
        >
          <el-option
            v-for="item in filteredPlanList"
            :key="item.planNo"
            :label="item.planNo"
            :value="item.planNo"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="采购计划名称" prop="planName">
        <el-input v-model="formData.planName" placeholder="请输入采购计划名称" disabled />
      </el-form-item>
      <el-form-item label="采购预算(万元)" prop="purchaseBudget">
        <el-input
          v-model="formData.purchaseBudget"
          type="number"
          placeholder="请输入采购预算(万元)"
          :disabled="disabled"
        />
      </el-form-item>
      <el-form-item label="采购方式" prop="purchaseMethod">
        <el-radio-group v-model="formData.purchaseMethod" :disabled="disabled">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.PURCHASE_METHOD)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="项目理由" prop="projectReason">
        <el-input
          v-model="formData.projectReason"
          type="textarea"
          placeholder="请输入项目理由"
          :disabled="disabled"
          rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        @click="auditForm"
        type="primary"
        :disabled="auditLoading || disabled"
        v-if="formData.status == 0 && formType != 'create'"
        >提交审核</el-button
      >
      <el-button @click="submitForm" type="primary" :disabled="formLoading || disabled"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { PurchaseManageApi, PurchaseManageVO } from '@/api/erp/purchasemanage'
import { PurchasePlanApi } from '@/api/erp/purchase/plan'
import { ElMessage } from 'element-plus'

/** 采购管理主表单 */
defineOptions({ name: 'PurchaseManageForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// -------------------------- 采购计划下拉框优化（初始加载200条） --------------------------
const allPlanList = ref([]) // 所有采购计划列表（完整缓存）
const filteredPlanList = ref([]) // 过滤后的显示列表
const planLoading = ref(false) // 加载状态

/** 加载所有采购计划（全量缓存，仅加载一次） */
const loadAllPlans = async () => {
  if (allPlanList.value.length > 0) return allPlanList.value

  planLoading.value = true
  try {
    const data = await PurchasePlanApi.getPurchasePlanqueryAll()
    allPlanList.value = data.list || []
    return allPlanList.value
  } catch (error) {
    ElMessage.error('加载采购计划列表失败，请重试')
    allPlanList.value = []
    return []
  } finally {
    planLoading.value = false
  }
}

/** 采购计划过滤方法（初始显示200条，搜索时全量过滤） */
const handlePlanFilter = async (query?: string) => {
  const allPlans = await loadAllPlans()

  // 1. 无搜索时只显示前200条，减轻渲染压力
  if (!query) {
    // 先取前200条基础数据
    const baseList = allPlans.slice(0, 200)
    // 检查已选项是否在基础列表中，不在则添加（保证回显）
    const selectedPlan = formData.value.purchasePlanNo
    if (selectedPlan && !baseList.some((item) => item.planNo === selectedPlan)) {
      const originalPlan = allPlans.find((item) => item.planNo === selectedPlan)
      if (originalPlan) {
        // 保持数组长度不超过201，避免过度渲染
        filteredPlanList.value = [originalPlan, ...baseList].slice(0, 200)
        return
      }
    }
    filteredPlanList.value = baseList
    return
  }

  // 2. 有搜索时基于全量数据过滤（保证搜索准确性）
  const lowerQuery = query.toLowerCase()
  let results = allPlans.filter(
    (item) =>
      item.planNo.toLowerCase().includes(lowerQuery) ||
      (item.planName && item.planName.toLowerCase().includes(lowerQuery))
  )

  // 确保已选项在结果中
  const selectedPlan = formData.value.purchasePlanNo
  if (selectedPlan && !results.some((item) => item.planNo === selectedPlan)) {
    const originalPlan = allPlans.find((item) => item.planNo === selectedPlan)
    if (originalPlan) {
      results.unshift(originalPlan)
    }
  }

  filteredPlanList.value = results
}
// ----------------------------------------------------------------------------

// 表单基础状态
const disabled = computed(() => formType.value === 'detail')
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const auditLoading = ref(false)

// 表单数据
const formData = ref<PurchaseManageVO & { status?: number }>({
  id: undefined,
  planId: undefined,
  planName: undefined,
  purchasePlanNo: undefined,
  purchaseBudget: undefined,
  purchaseMethod: undefined,
  projectReason: undefined,
  status: 0
})

// 表单校验规则
const formRules = reactive({
  purchasePlanNo: [{ required: true, message: '采购计划编号不能为空', trigger: 'change' }],
  purchaseBudget: [{ required: true, message: '采购预算(万元)不能为空', trigger: 'blur' }],
  purchaseMethod: [{ required: true, message: '采购方式不能为空', trigger: 'change' }],
  projectReason: [{ required: true, message: '项目理由不能为空', trigger: 'blur' }]
})

// 表单引用
const formRef = ref<InstanceType<
  typeof import('element-plus/lib/components/form/src/form.vue')
> | null>(null)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 初始加载200条数据
  await handlePlanFilter()

  // 修改时加载数据
  if (id) {
    formLoading.value = true
    try {
      const data = await PurchaseManageApi.getPurchaseManage(id)
      formData.value = { ...data }
      if (data.purchasePlanNo) {
        await handlePlanChange(data.purchasePlanNo)
      }
    } catch (error) {
      ElMessage.error('加载表单数据失败')
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

/** 处理采购计划编号变更 */
const handlePlanChange = async (planNo: string) => {
  const allPlans = await loadAllPlans()
  const matchedPlan = allPlans.find((item) => item.planNo === planNo)

  if (matchedPlan) {
    formData.value.planId = matchedPlan.id
    formData.value.planName = matchedPlan.planName || ''
  } else {
    formData.value.planId = undefined
    formData.value.planName = ''
  }
}

/** 监听采购计划编号变化 */
watch(
  () => formData.value.purchasePlanNo,
  async (newVal) => {
    if (!newVal) {
      formData.value.planId = undefined
      formData.value.planName = undefined
      return
    }
    await handlePlanChange(newVal)
  },
  { immediate: true }
)

/** 保存表单数据 */
const saveForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate()

  const data = { ...formData.value } as PurchaseManageVO
  data.purchaseBudget = Number(data.purchaseBudget)

  return formType.value === 'create'
    ? await PurchaseManageApi.createPurchaseManage(data)
    : await PurchaseManageApi.updatePurchaseManage(data)
}

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  formLoading.value = true
  try {
    await saveForm()
    message.success(
      formType.value === 'create' ? t('common.createSuccess') : t('common.updateSuccess')
    )
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    ElMessage.error('操作失败，请重试')
  } finally {
    formLoading.value = false
  }
}

/** 提交审核 */
const auditForm = async () => {
  auditLoading.value = true
  try {
    await saveForm()
    if (!formData.value.id) throw new Error('表单数据异常')

    await PurchaseManageApi.auditPurchaseManage(formData.value.id)
    message.success('提交审核成功')
    dialogVisible.value = false
    emit('success')
  } catch (error: any) {
    ElMessage.error(error.message || '审核失败，请重试')
  } finally {
    auditLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planId: undefined,
    planName: undefined,
    purchasePlanNo: undefined,
    purchaseBudget: undefined,
    purchaseMethod: undefined,
    projectReason: undefined,
    status: 0
  }
  formRef.value?.resetFields()
  handlePlanFilter().catch(() => {})
}
</script>